package com.gao.controller;

import com.gao.pojo.Payment;
import com.gao.service.IPaymentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;
import com.gao.entities.Result;

import java.util.List;

/**
 * @Author: suGar
 * @Date: 2022/10/13 9:39
 */
@RestController
@RequestMapping("/payment")
@Slf4j
public class PaymentController {

    private final DiscoveryClient discoveryClient;
    private final IPaymentService paymentService;

    @Value("${server.port}")
    private String serverPort;
    @Value("${spring.application.name}")
    private String serverName;

    public PaymentController(IPaymentService paymentService, DiscoveryClient discoveryClient) {
        this.paymentService = paymentService;
        this.discoveryClient = discoveryClient;
    }

    @GetMapping("{id}")
    public Result getPayment(@PathVariable("id") Integer id) {
        Payment payment = paymentService.getById(id);
        if (payment != null) {
            return Result.success("获取成功:" + serverPort, payment);
        }
        return Result.success("暂无数据:" + serverPort);
    }

    @GetMapping
    public Result getAllPayment() {
        return Result.success("获取成功:" + serverPort, paymentService.list());
    }

    @PostMapping
    public Result addPayment(@RequestBody Payment payment) {
        if (paymentService.saveOrUpdate(payment)) {
            return Result.success("添加成功:" + serverPort);
        }
        return Result.fail("添加失败:" + serverPort);
    }

    @GetMapping("/discovery")
    public Object discovery() {
        List<String> services = discoveryClient.getServices();
        for (String service : services) {
            log.info("service = " + service);
        }

        List<ServiceInstance> instances = discoveryClient.getInstances(serverName);
        for (ServiceInstance instance : instances) {
            log.info("instance = " + instance.getServiceId());
            log.info("instance = " + instance.getHost());
            log.info("instance = " + instance.getPort());
            log.info("instance = " + instance.getUri());
        }

        return this.discoveryClient;
    }
}
